package com.wanlian.netty.msg;

import com.wanlian.json.JsonStringUtil;
import com.wanlian.netty.ConstantCode;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 解码器
 *
 * @author ailianlu2
 */
public class PeerMsgDecoder extends ByteToMessageDecoder {

    final protected static char[] hexArray = "0123456789abcdef".toCharArray();

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
        try {
            // 记录包头开始的index
            int beginReader;
            while (true) {
                // 获取包头开始的index
                beginReader = byteBuf.readerIndex();
                // 标记包头开始的index
                byteBuf.markReaderIndex();
                // 判断是否可读
                if (!byteBuf.isReadable(4)) {
                    // 还原读指针
                    byteBuf.readerIndex(beginReader);
                    return;
                }

                int data = byteBuf.readInt();
                // 读到了协议的开始标志，结束while循环
                if (data == ConstantCode.HEAD_DATA) {
                    break;
                }

                // 未读到包头，略过一个字节
                // 每次略过，一个字节，去读取，包头信息的开始标记
                byteBuf.resetReaderIndex();
                byteBuf.readByte();
            }

            // 消息的长度
            // 判断是否可读
            if (!byteBuf.isReadable(4*3)) {
                // 还原读指针
                byteBuf.readerIndex(beginReader);
                return;
            }
            int version = byteBuf.readInt();
            int msgtype = byteBuf.readInt();
            int length = byteBuf.readInt();
            // 判断请求数据包数据是否到齐
            if (byteBuf.readableBytes() < length) {
                // 还原读指针
                byteBuf.readerIndex(beginReader);
                return;
            }
            byte[] body = new byte[length];

            byteBuf.readBytes(body);
            if (msgtype == ConstantCode.COMMON_MSG) {
                String content = new String(body, Charset.forName("UTF-8"));
                BaseMsg baseMsg = JsonStringUtil.readValue(content, BaseMsg.class);
                if (baseMsg != null) {
                    PeerMsg myMessage = new PeerMsg(new MsgHead(length, version, msgtype), baseMsg);
                    list.add(myMessage);
                }
                //System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
